package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.ProductMapper;
import cn.tedu.coolshark.pojo.dto.ProductDto;
import cn.tedu.coolshark.pojo.dto.ProductUpdateDto;
import cn.tedu.coolshark.pojo.entity.Product;
import cn.tedu.coolshark.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author liyang
 * @version 1.0
 * @package cn.tedu.coolshark.controller
 * @file ProductController.java
 * @description
 * @time 2024/8/13 下午8:48
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;
    /*小技巧：类和方法的注解自动拼接*/
    @RequestMapping("/insert")
    public void insert(@RequestBody ProductDto product){
        System.out.println("product:"+product);
        Product p = new Product();
        BeanUtils.copyProperties(product,p);
        p.setCreated(new Date());

        mapper.insert(p);
    }

    @RequestMapping("/select")
    /*专门在后台管理展示的Vo*/
    public List<ProductAdminVo> select(){
        return mapper.selectAdmin();
    }

    @RequestMapping("/selectTop")
    public List<ProductTopVO> selectTop(){
        return mapper.selectTop();
    }

    @RequestMapping("/selectIndex")
    public List<ProductIndexVO>selectIndex(){
        return mapper.selectIndex();
    }

    @RequestMapping("/selectById")
    public ProductDetailVO selectById(int id){
        mapper.addViewCount(id);

        return mapper.selectById(id);
    }

    @Value("${dirPath}")
    private String dirPath;
    @RequestMapping("/delete")
    public void delete(int id){
        //通过数据库表中的id先查询到图片的名称url
        String url = mapper.selectUrlById(id);
        //先得到文件夹路径➡与图片名进行拼接形成完整的图片路径➡删除文件夹中的图片
        new File(dirPath+"/"+url).delete();
        //删除数据库里面的数据
        mapper.deleteById(id);
    }

    @RequestMapping("/selectUpdate")
    public ProductUpdateVO selectUpdate(int id){

        return mapper.selectUpdate(id);
    }

    @RequestMapping("/update")
    public void update(@RequestBody ProductUpdateDto product){

        mapper.update(product);
    }

    @RequestMapping("/selectByCid")
    public List<ProductIndexVO> selectByCid(int id){
        return mapper.selectByCid(id);
    }

    @RequestMapping("/selectByWd")
    public List<ProductIndexVO> selectByWd(String wd){
        System.out.println("wd = " + wd);

        return mapper.selectByWd(wd);
    }

}
